<template>
  <div class="user-chat">
    <van-nav-bar
      class="app-nav-bar"
      title="sari同学"
      left-arrow
      @click-left="$router.back()"
    />

    <van-cell-group class="message-list" ref="message-list">
      <van-cell 
      title="单元格" 
      :title="item.msg"
      v-for="(item,index) in messages"
      :key="index" 
      />
    </van-cell-group>

    <van-cell-group class="send-message-wrap">
      <van-field v-model="value" placeholder="请输入消息" :border="false" />
      <van-button type="primary" size="samall" @click="onSend">发送</van-button>
    </van-cell-group>
  </div>
</template>
<script>
import io from "socket.io-client";
import {getItem,setItem} from '@/utils/storage'
export default {
  name: "UserChat",
  data() {
    return {
      mesage: "",
      socket:null,
      messages:getItem('chat-messages')||[]
    }
  },
  watch:{
    messages(){
        setItem('chat-messages',this.messages)
        this.$nextTick(()=>{
           this.scrollToBottom()
        })
        
    }
  },
  created() {
    // 建立连接
    const socket = io("http://ttapi.research.itcast.cn/")
    this.socket=socket
    socket.on("connect",  ()=> {
      console.log("建立连接成功");
    });
    // socket.on("event", function () {});
    // 断开连接
    socket.on("disconnect", () =>{
      console.log("dsad");
    })
    // 监听message事件，接收服务端消息
    socket.on('message',data=>{
        // console.log(data);
        // 把对方发送的消息存储到数组中
        this.messages.push(data)
    })
  },
  methods:{
      onSend(){
          const data={
           msg:this.mesage,
           timestamp:Date.now()
       }
       this.socket.emit('message',data)
    //    把用户发出的消息保存在数组中
       this.messages.push(data)
       this.message=''
      },
      scrollToBottom(){
          const list=this.$refs['message-list']
          list.scrollTop=list.scrollHeight
      }
  }
};
</script>
<style lang="less" scoped>
.message-list {
  position: fixed;
  top: 46px;
  left: 0;
  right: 0;
  bottom: 44px;
  overflow-y: auto;
}
.send-message-wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  padding: 0 14px;
  align-items: center;
}
</style>